<?php
declare (strict_types = 1);

namespace app\middleware;

use app\service\exception\ApiException;
use app\service\model\AdminAuthorityModel;
use app\service\model\AdminLogModel;
use app\service\model\AdminModel;
use app\service\model\AdminRoleModel;
use app\service\Token;
use app\service\Y;

class AdminCheckAuth
{
    /**
     * 后台访问权限验证
     * @param $request
     * @param \Closure $next
     * @return mixed|void
     * @throws ApiException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function handle($request, \Closure $next)
    {
        if (!$login_admin = Token::checkAdminToken()) {
            throw new ApiException(['msg' => '请先登录', 'errorCode' => 1001]);
        }

        // 检查是否有访问权限
        $path = '/admin/' . Request()->controller(true) . '/' . Request()->action(true);

        $no_check_auth_path_arr = [
            '/admin/index/index',
            '/admin/main/menu'
        ];

        if ($login_admin['username'] != 'admin') {
            // 是用短信登录，强制要求设置密码，然后重新是用帐号密码登录

            if (!in_array($path, $no_check_auth_path_arr)) {
                $auth = AdminAuthorityModel::where('path', '=', $path)->find();
                if (!$auth) {
                    throw new ApiException(['msg' => '非法访问路径']);
                }
                $admin = AdminModel::where('id', '=', $login_admin['admin_id'])->find();
                $admin_auth_ids = AdminRoleModel::getAuthIds($admin['roles'], 'arr');
                if (!in_array($auth->id, $admin_auth_ids)) {
                    throw new ApiException(['msg' => '没有访问权限，请联系管理员']);
                }
            }
        }

        // 验证通过  记录访问日志
        AdminLogModel::create([
            'admin_id' => session('admin.id'),
            'name' => session('admin.username'),
            'path' => $path,
            'method' => Request()->method(),
            'ip' => Request()->ip(),
            'roles' => session('admin.roles'),
            'param' => json_encode(input('param.'))
        ]);

        return $next($request);
    }
}
